<!--
 * @Description: 预警管理公共页
-->
<template>
  <div class="warning-manage">
    <div class="warning-manage__header">
      <el-radio-group v-model="dataViewDate" @change="queryTradeOrderTotal()">
        <el-radio-button label="1">今天</el-radio-button>
        <el-radio-button label="3">最近三天</el-radio-button>
        <el-radio-button label="7">最近七天</el-radio-button>
        <el-radio-button label="4" class="el-radio-button-inner-datepicker">
          <el-date-picker v-model="dataViewRange" type="daterange" align="right" unlink-panels range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" :picker-options="pickerOptions"
            @focus="focusPickerDate" @change="changeDataViewDate"></el-date-picker>
        </el-radio-button>
      </el-radio-group>
    </div>

    <div class="warning-manage__total">
      <div id="order_total_flex">
        <div class="total_row_item">
          <div class="order_content">
            <div class="order_total_title">预警次数</div>
            <div class="order_total_info">
              <span class="order_data">{{ totalData.warnNum || 0 }}</span>
            </div>
          </div>
          <div class="order_detail">
            <div class="order_content2">
              <div class="order_total_title">提示</div>
              <div class="order_total_info">
                <span class="order_data">{{ totalData.level1Num || 0 }}</span>
              </div>
            </div>
            <div class="order_content2">
              <div class="order_total_title">警告</div>
              <div class="order_total_info">
                <span class="order_data">{{ totalData.level2Num || 0 }}</span>
              </div>
            </div>
            <div class="order_content2">
              <div class="order_total_title">封号</div>
              <div class="order_total_info">
                <span class="order_data">{{
                  totalData.level3Num || 0
                }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="total_row_item">
          <div class="order_content">
            <div class="order_total_title">
              预警用户数量
              <!-- <el-popover placement="top-start" width="200" trigger="hover" :content="getDatatime('消费者支付金额合计')">
                <el-button slot="reference" @click.stop style="padding:0;border:0"><i
                    class="el-icon-question"></i></el-button>
              </el-popover> -->
            </div>
            <div class="order_total_info">
              <span class="order_data">{{ totalData.memberNum || 0}}</span>
            </div>
          </div>
        </div>
        <div class="total_row_item">
          <div class="order_content">
            <div class="order_total_title">预警订单（笔）</div>
            <div class="order_total_info">
              <span class="order_data">{{ totalData.orderNum || 0 }}</span>
            </div>
          </div>
        </div>
        <div class="total_row_item">
          <div class="order_content">
            <div class="order_total_title">
              预警门店数量
              <!-- <el-popover placement="top-start" width="200" trigger="hover" :content="getDatatime('消费者退款金额合计')">
                <el-button slot="reference" @click.stop style="padding:0;border:0"><i
                    class="el-icon-question"></i></el-button>
              </el-popover> -->
            </div>
            <div class="order_total_info">
              <span class="order_data">{{ totalData.storeNum || 0 }}</span>
            </div>
          </div>
        </div>
        <div class="total_row_item">
          <div class="order_content">
            <div class="order_total_title">
              预警订单金额（元）
              <!-- <el-popover placement="top-start" width="200" trigger="hover" :content="getDatatime('消费者确认收货已完成订单金额合计')">
                <el-button slot="reference" @click.stop style="padding:0;border:0"><i
                    class="el-icon-question"></i></el-button>
              </el-popover> -->
            </div>
            <div class="order_total_info">
              <span class="order_data">{{ totalData.moneyNum || '0.00' }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="warning-manage__form">
      <el-form :inline="true" :model="formInline" class="demo-form-inline" @keyup.enter.native="search()"
        id="orderSearchForm">
        <el-form-item label="店铺名称">
          <br />
          <el-input v-model="formInline.storeName" placeholder style="margin-left:-70px;width:200px"></el-input>
        </el-form-item>
        <el-form-item label="会员姓名">
          <br />
          <el-input v-model="formInline.nickName" placeholder style="margin-left:-70px;width:200px"></el-input>
        </el-form-item>
        <el-form-item label="会员手机号">
          <br />
          <el-input v-model="formInline.mobile" placeholder style="margin-left:-80px;width:200px"></el-input>
        </el-form-item>
        <el-form-item label="所属大区" v-if="userInfo.userType == '1'">
          <br />
          <el-select v-model="formInline.upOrgSeq" clearable filterable @change="selCore(formInline.upOrgSeq)"
            style="margin-left: -70px; width: 200px">
            <el-option v-for="item in corpList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属营销区域">
          <br />
          <el-select v-model="formInline.baseCode" clearable filterable @change="selbase(formInline.baseCode)"
            style="margin-left: -100px; width: 200px">
            <el-option v-for="item in RentalPayWay" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预警原因">
          <br />
          <el-input v-model="formInline.warnMessage" placeholder style="margin-left:-70px;width:200px"></el-input>
        </el-form-item>
        <el-form-item class="warning-manage__form--btn">
          <el-button type="primary" @click="search()" size="mini" icon="el-icon-search">查询</el-button>
          <el-button type="primary" @click="kong()" size="mini" icon="el-icon-delete">清空</el-button>
          <!-- <el-upload :action="action" :headers="headers" :show-file-list="false" :limit="1" :file-list="fileList"
            :before-upload="beforeUpload" :on-success="handleSuccess" :on-error="handleError" :disabled="uploadLoading"
            accept=".xls,.xlsx">
            <el-button type="warning" size="mini" icon="el-icon-edit" :loading="uploadLoading">批量发货</el-button>
          </el-upload> -->
          <el-button type="success" @click="exportExcel()" size="mini" icon="el-icon-s-data"
            :loading="exportLoading">导出</el-button>
          <el-button type="warning" @click="addRules()" size="mini" icon="el-icon-edit"
            v-if="userInfo.userType == '1'">预警规则配置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="warning-manage__table">
      <el-table :data="tableData" :header-cell-style="{ background: '#eef1f6', color: '#606266' }" border
        v-loading="loading">
        <el-table-column type="index" label="序号" align="center" width="60"></el-table-column>
        <el-table-column label="预警级别">
          <template slot-scope="scope">
            {{ getDictLabel('riskLevel', scope.row.riskLevel) }}
          </template>
        </el-table-column>
        <el-table-column label="触发预警数量" prop="currentNum"></el-table-column>
        <el-table-column label="手机号" prop="mobile" width="135px"></el-table-column>
        <el-table-column label="会员名称" prop="nickName"></el-table-column>
        <template v-if="userInfo.userType == '1'">
          <!-- <el-table-column label="订单客户编号" prop="orderId"></el-table-column> -->
          <el-table-column label="订单编号" prop="orderId"></el-table-column>
          <el-table-column label="店铺授权码" prop="authCode"></el-table-column>
        </template>
        <template v-else>
          <el-table-column label="订单金额" prop="totalMoney"></el-table-column>
          <el-table-column label="商品名称" prop="goodsName"></el-table-column>
          <el-table-column label="实付款" prop="totalMoney"></el-table-column>
        </template>
        <el-table-column label="店铺名称" prop="storeName" width="135px"></el-table-column>
        <el-table-column label="所属大区" prop="upOrgZone"></el-table-column>
        <el-table-column label="所属营销区域" prop="baseName"></el-table-column>
        <el-table-column label="预警原因" prop="warnMessage"></el-table-column>
        <el-table-column label="预警时间" prop="updateTime"></el-table-column>
        <el-table-column label="操作" :align="'center'" fixed="right" width="160">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="detailHandle(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 30, 50, 100, 150, 200]" :current-page="listQuery.current" :page-size="listQuery.size"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- <SendGoodsDialog :show.sync="show" :detail="curDetail" @refresh="onRefresh" /> -->
  </div>
</template>

<script>
import { queryWarnListPage, queryWarnHead, exportWarnList } from '@/api/warningManager';
import { getAllZone, getAllBase } from '@/api/addShopapply.js';
import { getDictLabel } from '@/dict';
import { formatDateTime } from '@/utils/format-data';
export default {
  components: {
    // SendGoodsDialog,
  },
  props: {
    // 1 商家兑换订单（云币）， 0 消费者兑换订单（酒币）
    type: { type: [String, Number], default: '1' },
  },
  data() {
    return {
      getDictLabel,
      userInfo: {},
      dataViewDate: '4',
      dataViewRange: '',
      totalData: {
        orderNum: 0,
        paymentNumber: 0,
        refundNumber: 0,
        orderFinishNum: 0,
        orderAcceptNum: 0,
        orderPostNum: 0,
        orderCancelNum: 0,
        paymentMon: 0,
        refundMon: 0,
        payerNum: 0,
        accumulativeTotal: 0,
        turnover: 0,
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '最近3天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            },
          },
        ],
      },
      loading: false,
      formInline: {
        storeName: '',
        memberName: '',
        memberPhone: '',
        upOrgSeq: '',
        baseCode: '',
        warnMessage: '',
      },
      dateRange: [],
      tableData: [],
      total: 0,
      listQuery: {
        current: 1,
        size: 100,
      },

      orgSeq: '', // 门店组织机构编码
      logininfo: null, // 登录信息

      corpList: [], // 大区列表
      RentalPayWay: [], //营销区域列表
      // 订单状态
      // orderStatusList: [
      //   {
      //     id: '0',
      //     name: '待支付',
      //   },
      //   {
      //     id: '1',
      //     name: '待发货',
      //   },
      //   {
      //     id: '2',
      //     name: '待收货',
      //   },
      //   {
      //     id: '3',
      //     name: '已完成',
      //   },
      //   {
      //     id: '4',
      //     name: '已取消',
      //   },
      //   {
      //     id: '-1',
      //     name: '已退款',
      //   },
      // ],
      // 付款方式
      payTypeEnum: {
        1: '现金支付',
        2: '货到付款',
        3: '线上支付',
        102: '酒币支付',
        105: '云币支付',
      },
      // 导出
      exportLoading: false,
      // 弹框相关
      show: false,
      curDetail: {},
    };
  },
  created() {
    var nowDay = this.getNowDay();
    var beginDay = this.getMonthOneDay();
    this.dataViewRange = [beginDay, nowDay];

    this.logininfo = localStorage.getItem('logininfo') || '{}';
    this.userInfo = JSON.parse(this.logininfo);
    this.orgSeq = this.userInfo.orgSeq;

    if(this.userInfo.userType != '1') {
      this.formInline.upOrgSeq = this.orgSeq
    }

    this.selCore(this.orgSeq);
    this._getAllZone();

    // this.getList();
    this.queryTradeOrderTotal();

  },
  methods: {
    formatDate(type) {
      if (type == '1') {
        return [formatDateTime(Date.now(), 'yyyy-MM-dd'), formatDateTime(Date.now(), 'yyyy-MM-dd')];
      } else if (type == '3') {
        return [formatDateTime(Date.now() - 3600 * 1000 * 24 * 3, 'yyyy-MM-dd'), formatDateTime(Date.now(), 'yyyy-MM-dd')];
      } else if (type == '7') {
        return [formatDateTime(Date.now() - 3600 * 1000 * 24 * 7, 'yyyy-MM-dd'), formatDateTime(Date.now(), 'yyyy-MM-dd')];
      }
    },
    search() {
      this.listQuery.current = 1;
      this.getList();
    },
    getList() {
      if (this.dataViewDate == '4') {
        this.formInline.startDate = this.dataViewRange[0];
        this.formInline.endDate = this.dataViewRange[1];

      } else {
        [this.formInline.startDate, this.formInline.endDate] = this.formatDate(this.dataViewDate);
      }

      const data = {
        size: this.listQuery.size,
        current: this.listQuery.current,
        condition: {
          ...this.formInline,
          startDate: this.formInline.startDate + ' 00:00:00',
          endDate: this.formInline.endDate + ' 23:59:59',
        },
        ascs: [],
        descs: [],
      };
      this.loading = true;
      queryWarnListPage(data)
        .then((res) => {
          this.tableData = res.records;
          this.total = res.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    onRefresh() {
      this.getList();
      this.curDetail = {};
    },
    kong() {
      if(this.userInfo.userType == '1') {
        this.formInline.upOrgSeq = '';
      }
      this.formInline.storeName = '';
      this.formInline.nickName = '';
      this.formInline.mobile = '';
      this.formInline.baseCode = '';
      this.formInline.warnMessage = '';
    },

    handleSizeChange(val) {
      this.listQuery.size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.current = val;
      this.getList();
    },
    selCore(value) {
      if (value != '' && value != undefined && value != null) {
        this.orgSeq = value;
        let data = {
          code: value,
        };
        getAllBase(data).then((res) => {
          this.RentalPayWay = res.result;
          this.formInline.jdName = '';
        });
      } else if (this.formInline.jdName != '') {
        this.orgSeq = this.formInline.jdName;
      } else {
        this.orgSeq = JSON.parse(this.logininfo).orgSeq;
      }
    },
    selbase(value) {
      if (value != '' && value != undefined && value != null) {
        this.orgSeq = value;
      } else if (this.formInline.zqName != '') {
        this.orgSeq = this.formInline.zqName;
      } else {
        this.orgSeq = JSON.parse(this.logininfo).orgSeq;
      }
    },

    _getAllZone() {
      let data = {};
      getAllZone(data).then((res) => {
        this.corpList = res.result;
      });
    },
    // 导出
    exportExcel() {
      this.exportLoading = true;
      const data = {
        // size: this.listQuery.size,
        size: 10000000,
        current: this.listQuery.current,
        condition: {
          ...this.formInline,
          startDate: this.dataViewRange[0] + ' 00:00:00',
          endDate: this.dataViewRange[1] + ' 23:59:59',
        },
        ascs: [],
        descs: [],
      };
      exportWarnList(data)
        .then((res) => {
          const byteCharacters = atob(res); //将base64转换为二进制字符串
          const byteNumbers = new Array(byteCharacters.length);
          for (let i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);  
          }
          const byteArray = new Uint8Array(byteNumbers);

          const link = document.createElement('a');
          let blob = new Blob([byteArray], { type: 'application/vnd.ms-excel' });
          link.style.display = 'none';
          //设置连接
          link.href = URL.createObjectURL(blob);
          link.download = `预警管理列表.xlsx`;
          document.body.appendChild(link);
          //模拟点击事件
          link.click();
          this.$message.success('导出成功');
        })
        .finally(() => {
          this.exportLoading = false;
        });
    },
    /* 获取时间+提示*/
    getDatatime(str) {
      return this.dataViewDate == 1
        ? '今天' + str
        : this.dataViewDate == 2
          ? '最近三天' + str
          : this.dataViewDate == 3
            ? '最近七天' + str
            : this.dataViewRange != null && this.dataViewRange != ''
              ? this.dataViewRange[0] + '至' + this.dataViewRange[1] + str
              : str;
    },
    // 切换订单的时间后的请求
    queryTradeOrderTotal() {
      let data = {};
      if (this.dataViewDate == '4') {
        data.startDate = this.dataViewRange[0];
        data.endDate = this.dataViewRange[1];
      } else {
        [data.startDate, data.endDate] = this.formatDate(this.dataViewDate);
      }
      this.getList();
      queryWarnHead({
        startDate: data.startDate + ' 00:00:00',
        endDate: data.endDate + ' 23:59:59',
        upOrgSeq: this.userInfo.userType == '1' ? '' : this.orgSeq
      }).then((res) => {
        this.totalData = res.result;
      });
    },
    //点击空白日期初始化
    focusPickerDate() {
      this.dataViewRange = '';
    },
    //点击头部时间选择切换为日期状态
    changeDataViewDate() {
      this.dataViewDate = '4';
      this.queryTradeOrderTotal();
    },
    addRules() {
      this.$router.push({
        name: 'warningManageConfig',
      });
    },

    detailHandle(row) {
      this.$router.push({
        name: 'warningManageDetail',
        params: {
          info: row,
        },
      });
    },

    getNowDay() {
      var date = new Date();
      var seperator1 = '-';
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = '0' + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate;
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate;
      return currentdate;
    },
    getMonthOneDay() {
      var date = new Date();
      // 计算30天前的日期
      date.setDate(date.getDate() - 30);

      var seperator1 = '-';
      var year = date.getFullYear();
      var month = date.getMonth() + 1; // 月份从0开始，需+1
      var day = date.getDate();

      // 补零逻辑
      month = month.toString().padStart(2, '0'); // 始终补零到两位
      day = day.toString().padStart(2, '0'); // 日期补零

      var targetDate = year + seperator1 + month + seperator1 + day;
      return targetDate;
    },
  },
};
</script>

<style lang="scss" scoped>
.warning-manage {
  &__header {
    /deep/ .el-radio-button-inner-datepicker {
      .el-radio-button__inner {
        padding: 0;
      }

      .el-input__inner {
        border: none;
        height: 38px;
      }
    }
  }

  &__total {
    margin-top: 20px;

    #order_total_flex {
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      justify-content: space-around;

      /deep/ .order_content {
        cursor: pointer;
        width: 200px;
        padding: 20px 0;
        margin: 0 auto;
        text-align: center;
        overflow: hidden;
        border-radius: 4px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);

        .order_total_title {
          color: #000;
        }

        .order_total_info {
          margin-top: 10px;
        }

        .order_data {
          font-size: 1.4em;
          font-weight: bold;
        }
      }

      /deep/ .order_detail {
        width: 200px;
        margin-top: 10px;
        display: flex;
        flex-direction: row;
        flex-wrap: nowrap;
        justify-content: space-between;
      }

      /deep/ .order_content2 {
        width: 60px;
        cursor: pointer;
        padding: 10px 0;
        margin: 0 1px;
        text-align: center;
        overflow: hidden;
        border-radius: 4px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
      }
    }
  }

  &__form {
    margin-top: 30px;
    margin-left: 35px;

    &--btn {
      margin-top: 40px;

      /deep/ .el-form-item__content {
        display: flex;
        align-items: center;
        gap: 10px;

        .el-button {
          margin: 0;
        }
      }
    }

    /deep/ #orderSearchForm {
      margin-left: -30px;
      padding: 0;
      display: inline-block;
      text-align: left;
    }
  }

  .line_line {
    border-left: 5px solid #dddddd;
    display: inline-block;
    height: 6.25rem;
    margin-left: -1px;
    padding: 0px 0px 0px 3px;
  }
}
</style>
